<?php

namespace IDock\Common\Tools;

class LoopXml
{
    public static function ArrayToXml($array, $root,$label='')
    {
        $array = self::checkLoop($array);
        return self::ToXML($array,$root,$label);
    }

    public static function ToXML($array, $root,$label='')
    {
        $xml = '';

        foreach ($array as $key => $val){

            if(strval($key) == 'loopString'){
                $xml .= $val;
                continue;
            }
            if(is_array($val)){
                if (!isset($val[0])) {
                    if (is_int($key)) {
                        $xml .= "<" . $label . ">" . self::ToXML($val, '', '') . "</" . $label . ">";
                    } else {
                        $xml .= "<" . $key . ">" . self::ToXML($val, '', '') . "</" . $key . ">";
                    }
                } else {
                    $xml .= self::ToXML($val, '',  $key);
                }
            }else{
                if(is_int($key)){
                    $xml .= "<" . $label . ">" . $val . "</" . $label . ">";
                }else{
                    $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
                }

            }

        }
        if($root){
            $xml = "<$root>".$xml."</$root>";
        }
        return $xml;

    }

    private static function checkLoop($array)
    {
        $xml = '';
        foreach ($array['body'] as $key => $val){
            if($key == 'loop'){
                //处理重复键
                foreach ($val as $loopKey => $row){
                    if(is_array($row)){
                        $xml .= self::ToXML($row, '',  $loopKey);
                    }else{
                        $xml .= "<" . $loopKey . ">" . self::ToXML($row, '') . "</" . $loopKey . ">";
                    }
                    $array['body']['loopString'] = $xml;
                }
                unset($array['body']['loop']);
            }
        }
        return $array;
    }
}
